package com.yihaodian.zk;

import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.recipes.lock.LockListener;
import org.apache.zookeeper.recipes.lock.WriteLock;

public class BlockingWriteLock {
	private CountDownLatch signal = new CountDownLatch(1);
	WriteLock writeLock;

	public BlockingWriteLock(String name, ZooKeeper zookeeper, String path,
			List<ACL> acls) {
		this.writeLock = new WriteLock(zookeeper, path, acls,
				new SyncLockListener());
	}

	public void lock() throws InterruptedException, KeeperException {
		writeLock.lock();
		signal.await();
	}

	public void unlock() {
		writeLock.unlock();
	}

	class SyncLockListener implements LockListener {
		@Override
		public void lockAcquired() {
			signal.countDown();
		}

		@Override
		public void lockReleased() {

		}
	}
}
